<template>
  <div class="diy_edit slides_edits" id="slides_edit">
    <el-form
      :model="form"
      ref="ruleFormRef"
      :rules="rules"
      label-width="auto"
      class="edit_slides_form"
      size="large"
    >
      <el-row class="row_e">
        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="轮播图" prop="img">
            <el-upload
              class="avatar-uploader"
              drag
              accept="image/gif, image/jpeg, image/png, image/jpg"
              action=""
              :http-request="uploadimg"
              :show-file-list="false"
            >
              <img
                v-if="form.img"
                :src="$fullUrl($banseUrl, form.img)"
                class="avatar"
              />
              <el-icon v-else><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="footer">
        <el-button type="primary" @click="Onsubmit" size="large"
          >提交</el-button
        >
        <el-button @click="cancel()" size="large">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { ref, onMounted } from "vue";
import { $post, $get } from "@/api/Api.js";
import storageHelper from "@/libs/StorageHelper";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import {
  $get_auth,
  func,
  paramsFun,
  $fullUrl,
  formatDate,
  $banseUrl,
  $check_action,
  $getUrlParams,
  filterSensitiveWords,
} from "@/utils/utils.js";
let router = useRouter();
let store = useStore();
let token = storageHelper.getToken() || null;
let UserInfo = storageHelper.getUserInfo();
let slides_id = $getUrlParams().slides_id;
let url_add = ref("/api/slides/add");
let url_set = ref("/api/slides/set");
let url_upload = ref("/api/slides/upload?");
let url_get_obj = ref("/api/slides/get_obj");
let title = ref("slides");
let field = ref("slides_id");

let form = ref({
  slides_id: 0,
  title: "",
  content: "",
  url: "",
  img: "",
  hits: 0,
});

let ruleFormRef = ref(null);
let rules = ref({
  title: [
    {
      required: true,
      message: "标题不能为空",
      trigger: "blur",
    },
  ],
});
// 上传封面图
let uploadimg = (param) => {
  uploadFile(param.file, "img");
};
/**
 * 上传封面图
 * @param {Object} file 文件对象
 * @param {key} 保存键名
 */
const uploadFile = (file, key = "img") => {
  var formobj = new FormData(); // FormData 对象
  formobj.append("file", file); // 文件对象
  $upload(url_upload.value, formobj, function (json) {
    if (json.result) {
      form.value[key] = json.result.url;
    } else {
      ElMessage.error("上传失败！");
    }
  });
};
/**
 * 上传文件
 * @param {String} url 请求地址
 * @param {Object} body 请求参数
 * @param {Funciton} func 回调函数，可以为空，为空则采用await返回值
 * @return {Object} 返回请求结果
 */
let $upload = async (url, body, func) => {
  url = url.replace("~/", $banseUrl);
  if (func) {
    // 如果回调函数存在, 则采用异步
    $post(url, body, {
      headers: {
        "x-auth-token": token,
        "Content-Type": "multipart/form-data",
      },
    })
      .then((res) => {
        func(res);
      })
      .catch((res) => {
        func(res);
      });
  } else {
    // 否则采用同步
    var res = await $post(url, body, {
      headers: {
        "x-auth-token": token,
        "Content-Type": "multipart/form-data",
      },
    });
    return res;
  }
};
// 点击取消
let cancel = () => {
  router.go(-1);
};
// 点击提交
let Onsubmit = async () => {
  let valid = await ruleFormRef.value.validate();
  if (valid) {
    if (slides_id) {
      // 编辑
      $post(url_set.value + "?slides_id=" + slides_id, form.value).then(
        (res) => {
          if (res.result) {
            ruleFormRef.value.resetFields();
            router.push("/home/slides/table");
            ElMessage.success("提交成功！");
          } else if (res.error) {
            ElMessage.error(res.error.message);
          }
        }
      );
    } else {
      // 新增
      $post(url_add.value, form.value).then((res) => {
        if (res.result) {
          ruleFormRef.value.resetFields();
          router.push("/home/slides/table");
          ElMessage.success("提交成功！");
        } else if (res.error) {
          ElMessage.error(res.error.message);
        }
      });
    }
  } else {
    ElMessage.error(msg);
  }
};
// 获取详情
let get_slides_obj = async () => {
  var list = await $get("/api/slides/get_obj?slides_id=" + slides_id);
  form.value = list.result.obj;
};
onMounted(() => {
  if (slides_id) {
    get_slides_obj();
  }
});
</script>

<style scoped lang="less">
.diy_edit {
  width: 100%;
  .edit_slides_form {
    max-width: 60%;
    margin: 90px auto;
    .fn {
      width: 100%;
    }
  }
  img {
    width: 100px;
    height: 100px;
  }
  .edit_list_slides_sell {
    width: 80%;
    margin: 90px auto;
  }
  .footer {
    text-align: center;
  }
}
</style>
